package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class EmployeeRealm extends AuthorizingRealm {

    @Setter
    private IEmployeeService service;

    @Setter
    private IRoleService roleService;

    @Setter
    private IPermissionService permissionService;

    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        获取当前的登录用户对象
        Employee emp = (Employee) principals.getPrimaryPrincipal();

        if(emp == null)
        {
           return null;
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = null;
        Set<String> permissions = null;

//        判断用户是不是超级管理员，是的话拥有所有的权限和所有的角色
        if(emp.isAdmin())
        {
            System.out.println("我是超级管理员");
            roles = new HashSet<>();
            permissions = new HashSet<>();

            List<Role> list = roleService.selectAll();
            for (Role role : list) {
                roles.add(role.getSn());

            }
            permissions.add("*:*");
        }
        else
        {
            //        不管是查询用户的角色还是权限，都是shiro帮我进行判断了，不用我们进行比较，我们只需要封装成shiro可操作的info对象即可
            //        根据用户的id查询用户所拥有的角色和权限
            roles = roleService.selectRoleByEmployeeId(emp.getId());
            permissions = permissionService.queryPermissionResourceByEmpId(emp.getId());

        }
        info.setRoles(roles);
        info.setStringPermissions(permissions);

        return info;
    }

    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        根据用户名查询用户是否存在
        String username = (String) token.getPrincipal();

//        如果为null说明查不到
        Employee employee = service.checkUsername(username);
        if (employee == null)
        {
            return null;
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPassword(),
//                为密码加盐
                ByteSource.Util.bytes(employee.getUsername()),
                getName());
        System.out.println(employee.getPassword());
        return info;
    }
}
